﻿Imports QLPhuTungOto.Data
Imports QLPhuTungOto.Bus
Imports DevExpress.XtraEditors
Imports DevExpress.XtraGrid.Controls

Public Class ucQLBanHang
    Dim db As New QLPhuTungOtoDataContext
    Dim ptBUS As New PhuTungBUS
    Dim khBUS As New KhachHangBUS
    Dim TrangHienTai As Integer = 1
    Dim TongSoTrang As Integer = 1
    Dim SoDongTrenTrang As Integer = 0

    Private Sub ucQLBanHang_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
           Dim lstKhachHang As New List(Of KhachHang)
        lstKhachHang = khBUS.LayDS()
        SearchLookUpEdit1.Properties.DataSource = lstKhachHang
        SearchLookUpEdit1.Properties.ValueMember = "MaKhachHang"
        SearchLookUpEdit1.Properties.DisplayMember = "TenKhachHang"
        UcPhanTrang1.txtSoDongCuaTrang.Text = HamHoTro.DocThongSo("config.config", "PhanTrangBanHang", "200")

        SoDongTrenTrang = Integer.Parse(UcPhanTrang1.txtSoDongCuaTrang.Text)
        TinhSoTrang()
        LoadDanhSachPhuTung()
        Dim f As Form = Me.FindForm()
        If f Is Nothing Then
            Return
        End If
        f.KeyPreview = True
        AddHandler f.KeyDown, AddressOf Form_KeyDown
    End Sub

    Dim lstPhuTung As List(Of PhuTung)
    Private Sub LoadDanhSachPhuTung()
        'lstPhuTung = New List(Of PhuTung)
        'lstPhuTung = db.PhuTung.ToList()
        'gcDSPhuTung.DataSource = ptBUS.LoadDSPhuTung()
        SoDongTrenTrang = Integer.Parse(Integer.Parse(UcPhanTrang1.txtSoDongCuaTrang.Text))
        gcDSPhuTung.DataSource = ptBUS.LayBang((TrangHienTai - 1) * SoDongTrenTrang, SoDongTrenTrang)
        UcPhanTrang1.lblTrangHienTai.Text = TrangHienTai.ToString + "/" + TongSoTrang.ToString
    End Sub

    Private Sub LoadDanhSachPhuTung2()
        'lstPhuTung = New List(Of PhuTung)
        'lstPhuTung = db.PhuTung.ToList()
        gcDSPhuTung.DataSource = ptBUS.LoadDSPhuTung()
        'SoDongTrenTrang = Integer.Parse(Integer.Parse(UcPhanTrang1.txtSoDongCuaTrang.Text))
        'gcDSPhuTung.DataSource = ptBUS.LayBang((TrangHienTai - 1) * SoDongTrenTrang, SoDongTrenTrang)
        'UcPhanTrang1.lblTrangHienTai.Text = TrangHienTai.ToString + "/" + TongSoTrang.ToString
    End Sub

    Dim _dataTable As New DataTable()
    Private Sub InitGioHang()

        _dataTable.TableName = "DataTable"

        _dataTable.Columns.Add(New DataColumn("Ma", GetType(String)))
        _dataTable.Columns.Add(New DataColumn("Ten", GetType(String)))
        _dataTable.Columns.Add(New DataColumn("SoLuong", GetType(String)))
        _dataTable.Columns.Add(New DataColumn("ThanhTien", GetType(String)))
        _dataTable.Columns.Add(New DataColumn("GiaBan", GetType(String)))
        _dataTable.Columns.Add(New DataColumn("HangTon", GetType(String)))

        gcGioHang.DataSource = _dataTable

    End Sub

    Private Function KiemTraTonTai(ByVal a As String, ByVal b As DevExpress.XtraGrid.Views.Grid.GridView) As Integer
        If b.RowCount = 0 Then
            Return -1
        End If
        Dim old As Integer = Integer.Parse(b.GetRowCellValue(b.FocusedRowHandle, "SoLuong"))
        For i = 0 To b.RowCount - 1
            b.FocusedRowHandle = i
            If b.GetRowCellValue(b.FocusedRowHandle, "Ma") = a Then
                Return i

            End If
        Next
        Return -1
    End Function

    Private Function KiemTraHangTon(ByVal soLuongGH As Integer, ByVal soLuongTon As Integer) As Boolean
        If soLuongGH > soLuongTon Then
            Return True
        End If
        Return False
    End Function

    Private Sub TinhTongTien()
        total = 0
        For i = 0 To gvGioHang.RowCount - 1
            total = total + gvGioHang.GetRowCellValue(i, "ThanhTien")
        Next
        Label2.Text = total.ToString("c0")
    End Sub

    Private Sub LaySanPham()

        Dim cthd As New ChiTietHoaDon
        Dim index As Integer = gvDSPhuTung.FocusedRowHandle

        If gvDSPhuTung.GetRowCellValue(index, "SoLuong") < seSoLuong.Value Then
            XtraMessageBox.Show("Số lương hàng tồn không đủ")
            seSoLuong.Value = 0
        Else
            If gvGioHang.RowCount >= 0 Then
                Dim i As Integer = KiemTraTonTai(gvDSPhuTung.GetRowCellValue(index, "MaPhuTung"), gvGioHang)
                If i >= 0 Then
                    gvGioHang.FocusedRowHandle = i

                    Dim old As Integer = gvGioHang.GetRowCellValue(i, "SoLuong")
                    Dim temp As Integer = 0
                    temp = old + seSoLuong.Value

                    If KiemTraHangTon(temp, gvDSPhuTung.GetRowCellValue(gvDSPhuTung.FocusedRowHandle, "SoLuong")) = True Then
                        XtraMessageBox.Show("Số lượng hàng tồn không đủ")
                        gvGioHang.SetRowCellValue(i, gvGioHang.Columns("SoLuong"), old)
                    Else
                        gvGioHang.SetRowCellValue(i, gvGioHang.Columns("SoLuong"), temp)
                    End If

                    gvGioHang.SetRowCellValue(i, gvGioHang.Columns("GiaBan"), gvDSPhuTung.GetRowCellValue(index, "GiaBan"))

                    Dim thanhTien As Integer = Integer.Parse(gvDSPhuTung.GetRowCellValue(index, gvDSPhuTung.Columns("GiaBan"))) * Integer.Parse(gvGioHang.GetRowCellValue(i, "SoLuong"))
                    gvGioHang.SetRowCellValue(i, gvGioHang.Columns("ThanhTien"), thanhTien.ToString("c0"))
                Else
                    gvGioHang.AddNewRow()
                    Dim index2 As Integer = gvGioHang.FocusedRowHandle
                    gvGioHang.SetRowCellValue(index2, gvGioHang.Columns("Ma"), gvDSPhuTung.GetRowCellValue(index, "MaPhuTung"))
                    gvGioHang.SetRowCellValue(index2, gvGioHang.Columns("Ten"), gvDSPhuTung.GetRowCellValue(index, "TenPhuTung"))
                    gvGioHang.SetRowCellValue(index2, gvGioHang.Columns("SoLuong"), seSoLuong.Value)

                    Dim thanhTien As Integer = Integer.Parse(gvDSPhuTung.GetRowCellValue(index, gvDSPhuTung.Columns("GiaBan"))) * Integer.Parse(seSoLuong.Value)
                    gvGioHang.SetRowCellValue(index2, gvGioHang.Columns("ThanhTien"), thanhTien.ToString("c0"))
                    gvGioHang.SetRowCellValue(index2, gvGioHang.Columns("GiaBan"), gvDSPhuTung.GetRowCellValue(index, "GiaBan"))
                    gvGioHang.SetRowCellValue(index2, gvGioHang.Columns("HangTon"), gvDSPhuTung.GetRowCellValue(index, "SoLuong"))
                End If
            End If
            gvGioHang.UpdateCurrentRow()
        End If

        'Dim donGia As Integer = Integer.Parse(gvDSPhuTung.GetRowCellValue(index, gvDSPhuTung.Columns("colGiaBan")))



        'gvGioHang.RefreshData()
    End Sub

    Private Sub GetHoaDon()
        Dim s As Integer
        If SearchLookUpEdit1.Text = "" Then
            s = 1
        Else
            s = SearchLookUpEdit1.EditValue
        End If
        Dim hd As New HoaDon With
            {
                .MaKhachHang = s,
                .NgayXuat = DateTime.Now(),
                .TongTien = 1,
                .GhiChu = ""
            }

        Dim ct As ChiTietHoaDon
        Dim lstChiTiet As New List(Of ChiTietHoaDon)
        For i = 0 To _dataTable.Rows.Count - 1
            ct = New ChiTietHoaDon With
                 {
                     .MaPhuTung = _dataTable.Rows(i)(0).ToString(),
                     .SoLuong = _dataTable.Rows(i)(2).ToString(),
                     .ThanhTien = _dataTable.Rows(i)(3).ToString(),
                     .Gia = _dataTable.Rows(i)(4).ToString()
                }
            lstChiTiet.Add(ct)
        Next

        Dim ptBUS As New PhuTungBUS
        ptBUS.CapNhatSoLuong(lstChiTiet)
        Dim hdBUS As New HoaDonBUS
        hdBUS.ThemHoaDon(hd, lstChiTiet)

        'gcDSPhuTung.DataSource = ptBUS.LayBang()
    End Sub


    Dim total As Integer = 0
    Private Sub btnThemGioHang_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemGioHang.Click
        LaySanPham()
        TinhTongTien()
    End Sub

    Private Sub btnNhap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNhap.Click

        Try
            GetHoaDon()
            XtraMessageBox.Show("Thêm hóa đơn thành công")

            _dataTable.Clear()
            db = New QLPhuTungOtoDataContext
            'lstPhuTung = db.PhuTung.ToList()
            gcDSPhuTung.DataSource = ptBUS.LoadDSPhuTung()
        Catch ex As Exception
            XtraMessageBox.Show("Xảy ra lỗi khi thêm hóa đơn")
        End Try


        'MessageBox.Show("Insert hóa đơn thành công")

    End Sub


    Private Sub gvGioHang_CellValueChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gvGioHang.CellValueChanged
        Try
            If e.Column.Caption = "Số lượng" And flag = True Then

                If Integer.Parse(e.Value) > Integer.Parse(gvGioHang.GetRowCellValue(gvGioHang.FocusedRowHandle, "HangTon")) Then
                    XtraMessageBox.Show("Ko du hang ton")
                    gvGioHang.SetRowCellValue(gvGioHang.FocusedRowHandle, "SoLuong", oldSL)
                    gvGioHang.SetRowCellValue(gvGioHang.FocusedRowHandle, "ThanhTien", oldTT.ToString("c0"))
                    flag = False
                Else
                    Dim thanhTien As Integer = 0
                    thanhTien = Integer.Parse(gvGioHang.GetRowCellValue(gvGioHang.FocusedRowHandle, "SoLuong")) * Integer.Parse(gvGioHang.GetRowCellValue(gvGioHang.FocusedRowHandle, "GiaBan"))
                    gvGioHang.SetRowCellValue(gvGioHang.FocusedRowHandle, "ThanhTien", thanhTien.ToString("c0"))
                End If
            End If
        Catch ex As Exception

        End Try
        TinhTongTien()

    End Sub

    Dim oldSL As Integer = 0
    Dim oldTT As Integer = 0
    Dim flag As Boolean = False
    Private Sub gvGioHang_RowCellClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs) Handles gvGioHang.RowCellClick
        oldSL = gvGioHang.GetRowCellValue(gvGioHang.FocusedRowHandle, "SoLuong")

        oldTT = gvGioHang.GetRowCellValue(gvGioHang.FocusedRowHandle, "ThanhTien")
        flag = True
    End Sub


    Private Sub CapNhatStatusSoLuongPhuTung()
        ToolStripStatusLabel1.Text = "Tổng số lượng: " + gvDSPhuTung.RowCount.ToString()
    End Sub

    Private Sub CapNhatStatusMaGiaSoLuongPhuTung()
        Try
            ToolStripStatusLabel2.Text = "Mã: " + gvDSPhuTung.GetRowCellValue(gvDSPhuTung.FocusedRowHandle, "MaPhuTung").ToString()
            ToolStripStatusLabel3.Text = "Giá: " + gvDSPhuTung.GetRowCellValue(gvDSPhuTung.FocusedRowHandle, "GiaBan").ToString()
            ToolStripStatusLabel4.Text = "Còn " + gvDSPhuTung.GetRowCellValue(gvDSPhuTung.FocusedRowHandle, "SoLuong").ToString() + _
                " " + gvDSPhuTung.GetRowCellValue(gvDSPhuTung.FocusedRowHandle, "DonVi").ToString()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub gvDSPhuTung_FocusedRowChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gvDSPhuTung.FocusedRowChanged
        CapNhatStatusMaGiaSoLuongPhuTung()
    End Sub


    Private Sub gvGioHang_CellValueChanging(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gvGioHang.CellValueChanging
        If Not IsNumeric(e.Value) Then
            gvGioHang.SetRowCellValue(gvGioHang.FocusedRowHandle, "SoLuong", oldSL)
            gvGioHang.SetRowCellValue(gvGioHang.FocusedRowHandle, "ThanhTien", oldTT)
            flag = False
        End If
    End Sub


    Private Sub SearchLookUpEdit1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchLookUpEdit1.Click
        Dim lstKhachHang As New List(Of KhachHang)
        lstKhachHang = khBUS.LayDS()
        'SearchLookUpEdit1.Properties.DataSource = lstKhachHang
        'SearchLookUpEdit1.Properties.ValueMember = "MaKhachHang"
        'SearchLookUpEdit1.Properties.DisplayMember = "TenKhachHang"
        'SearchLookUpEdit1.ShowPopup()
    End Sub

    Private Sub gvDSPhuTung_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gvDSPhuTung.DoubleClick
        Dim pt As New PhuTung
        Dim i As Integer = gvDSPhuTung.FocusedRowHandle
        pt.Stt = gvDSPhuTung.GetRowCellValue(i, "Stt")
        pt.MaPhuTung = gvDSPhuTung.GetRowCellValue(i, "MaPhuTung")
        pt.TenPhuTung = gvDSPhuTung.GetRowCellValue(i, "TenPhuTung")
        pt.SoLuong = gvDSPhuTung.GetRowCellValue(i, "SoLuong")
        pt.GiaBan = gvDSPhuTung.GetRowCellValue(i, "GiaBan")
        pt.DonVi = gvDSPhuTung.GetRowCellValue(i, "DonVi")

        pt.LoaiPhuTung = New LoaiPhuTung()
        pt.NhaCungCap = New NhaCungCap()
        pt.HinhAnh = New HinhAnh()
        pt.LoaiPhuTung.TenLoaiPhuTung = gvDSPhuTung.GetRowCellValue(i, "TenLoaiPhuTung")
        pt.NhaCungCap.TenNhaCungCap = gvDSPhuTung.GetRowCellValue(i, "TenNhaCungCap")
        pt.HinhAnh.DuongDan = gvDSPhuTung.GetRowCellValue(i, "DuongDan")

        Dim frmChiTiet As New frmChiTietPT(pt)
        frmChiTiet.ShowDialog()
    End Sub


    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        gvGioHang.DeleteSelectedRows()

    End Sub

    Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        gcGioHang.DataSource = Nothing
        TinhTongTien()
    End Sub


    Private Sub gvGioHang_RowCountChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gvGioHang.RowCountChanged
        If gvGioHang.RowCount = 0 Then
            btnNhap.Enabled = False
        Else
            btnNhap.Enabled = True

        End If
    End Sub

    Private Sub ucQLBanHang_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
        

    End Sub

    Private Sub UcPhanTrang1_SuaSoDongTrenTrang() Handles UcPhanTrang1.SuaSoDongTrenTrang
        Try
            SoDongTrenTrang = Integer.Parse(UcPhanTrang1.txtSoDongCuaTrang.Text)

            If SoDongTrenTrang > 0 Then
                TinhSoTrang()
                TrangHienTai = 1
                LoadDanhSachPhuTung()
                HamHoTro.GhiThongSo("config.config", "PhanTrangBanHang", UcPhanTrang1.txtSoDongCuaTrang.Text.Trim)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub UcPhanTrang1_TrangCuoi_Click() Handles UcPhanTrang1.TrangCuoi_Click
        Try
            TrangHienTai = TongSoTrang
            LoadDanhSachPhuTung()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub UcPhanTrang1_TrangDau_Click() Handles UcPhanTrang1.TrangDau_Click
        Try
            TrangHienTai = 1
            LoadDanhSachPhuTung()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub UcPhanTrang1_TrangSau_Click() Handles UcPhanTrang1.TrangSau_Click
        Try
            If TrangHienTai < TongSoTrang Then
                TrangHienTai += 1
                LoadDanhSachPhuTung()
            End If
        Catch ex As Exception

        End Try


    End Sub

    Private Sub UcPhanTrang1_TrangTruoc_Click() Handles UcPhanTrang1.TrangTruoc_Click
        Try
            If TrangHienTai > 1 Then
                TrangHienTai -= 1
                LoadDanhSachPhuTung()
            End If
        Catch ex As Exception

        End Try


    End Sub

    Private Function TinhSoTrang() As Integer
        Dim st As Integer = 0
        Try

            Dim soluongpt As Integer = ptBUS.DemSoLuongPhuTung()
            st = (soluongpt \ SoDongTrenTrang)

            If soluongpt Mod SoDongTrenTrang <> 0 Then
                st += 1
            End If

            TongSoTrang = st

        Catch ex As Exception

        End Try
        Return st
    End Function


    Dim flag1 As Boolean = False
    Dim isDel As Boolean = False
    Private Sub Form_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
        If TypeOf (Me.ActiveControl) Is FindControl Then
            Dim c As FindControl = Me.ActiveControl
            Dim s As String = c.Controls(0).Controls(5).Text
            If e.KeyCode = Keys.Back Then
                isDel = True
            End If

            If isDel = False Then
                If flag1 = False Then
                    LoadDanhSachPhuTung2()
                    flag1 = True
                End If
            ElseIf isDel = True AndAlso s.Count = 1 Then
                LoadDanhSachPhuTung()
                flag1 = False
                isDel = False
            End If
        End If
    End Sub

    'Private Function CapNhatTongTien() As Integer

    'End Function

    Private Sub LabelControl1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles LabelControl1.Paint
        Try
            If TrangThai.ThayDoiKhachHang_BanHang Then              
                Dim lstKhachHang As New List(Of KhachHang)
                lstKhachHang = khBUS.LayDS()
                SearchLookUpEdit1.Properties.DataSource = lstKhachHang
                SearchLookUpEdit1.Properties.ValueMember = "MaKhachHang"
                SearchLookUpEdit1.Properties.DisplayMember = "TenKhachHang"
                TrangThai.ThayDoiKhachHang_BanHang = False
            End If


            If TrangThai.ThayDoiPhuTung_BanHang Then
                LoadDanhSachPhuTung()
                TrangThai.ThayDoiPhuTung_BanHang = False
            End If
           
            SearchLookUpEdit1.Properties.NullText = ""          

            InitGioHang()
            CapNhatStatusSoLuongPhuTung()
            btnNhap.Enabled = False

            Dim f As Form = Me.FindForm()
            If f Is Nothing Then
                Return
            End If
            f.KeyPreview = True
            AddHandler f.KeyDown, AddressOf Form_KeyDown
        Catch ex As Exception

        End Try
    End Sub

    Private Sub LinkLabel2_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
        

        GridControl1.DataSource = ptBUS.LoadDSPhuTung()


        Dim op As New DevExpress.XtraPrinting.XlsExportOptions
        op.ShowGridLines = True
        Dim a As New FolderBrowserDialog

        If a.ShowDialog() = DialogResult.OK Then
            GridControl1.ExportToXls(a.SelectedPath + "/Báo giá.xls".ToString(), op)

        End If
    End Sub

    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Dim frm As New frmThemKhachHang
        frm.ShowDialog()

        Dim lstKhachHang As New List(Of KhachHang)
        lstKhachHang = khBUS.LayDS()
        SearchLookUpEdit1.Properties.DataSource = lstKhachHang
        SearchLookUpEdit1.Properties.ValueMember = "MaKhachHang"
        SearchLookUpEdit1.Properties.DisplayMember = "TenKhachHang"
    End Sub
End Class
